const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

router.use(authenticateToken);

// ========================================
// 标签管理
// ========================================

// 获取标签列表
router.get('/tags', async (req, res) => {
    try {
        const userId = req.user.user_id;
        const [tags] = await db.query(
            'SELECT * FROM tags WHERE user_id = ? ORDER BY use_count DESC',
            [userId]
        );
        res.json({ code: 200, data: tags });
    } catch (error) {
        console.error('获取标签失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 创建标签
router.post('/tags', async (req, res) => {
    try {
        const { tag_name, color } = req.body;
        const userId = req.user.user_id;

        const [result] = await db.query(
            'INSERT INTO tags (user_id, tag_name, color) VALUES (?, ?, ?)',
            [userId, tag_name, color || '#4285f4']
        );

        res.json({ code: 200, message: '标签创建成功', data: { tag_id: result.insertId } });
    } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
            return res.status(400).json({ code: 400, message: '标签已存在' });
        }
        console.error('创建标签失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 删除标签
router.delete('/tags/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.user_id;

        await db.query('DELETE FROM tags WHERE tag_id = ? AND user_id = ?', [id, userId]);
        res.json({ code: 200, message: '标签删除成功' });
    } catch (error) {
        console.error('删除标签失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// ========================================
// 用户设置
// ========================================

// 获取用户设置
router.get('/settings', async (req, res) => {
    try {
        const userId = req.user.user_id;
        const [[settings]] = await db.query(
            'SELECT * FROM user_settings WHERE user_id = ?',
            [userId]
        );

        if (!settings) {
            // 创建默认设置
            await db.query(
                'INSERT INTO user_settings (user_id) VALUES (?)',
                [userId]
            );
            return res.json({
                code: 200,
                data: {
                    user_id: userId,
                    theme_mode: 'light',
                    enable_notifications: 1,
                    enable_budget_alert: 1,
                    currency: 'CNY'
                }
            });
        }

        res.json({ code: 200, data: settings });
    } catch (error) {
        console.error('获取设置失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 更新用户设置
router.put('/settings', async (req, res) => {
    try {
        const { theme_mode, enable_notifications, enable_budget_alert, default_book_id } = req.body;
        const userId = req.user.user_id;

        await db.query(
            `INSERT INTO user_settings (user_id, theme_mode, enable_notifications, enable_budget_alert, default_book_id)
             VALUES (?, ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE
                theme_mode = COALESCE(VALUES(theme_mode), theme_mode),
                enable_notifications = COALESCE(VALUES(enable_notifications), enable_notifications),
                enable_budget_alert = COALESCE(VALUES(enable_budget_alert), enable_budget_alert),
                default_book_id = COALESCE(VALUES(default_book_id), default_book_id)`,
            [userId, theme_mode, enable_notifications, enable_budget_alert, default_book_id]
        );

        res.json({ code: 200, message: '设置已保存' });
    } catch (error) {
        console.error('更新设置失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// ========================================
// 消费趋势分析
// ========================================

// 获取趋势数据
router.get('/trends', async (req, res) => {
    try {
        const { book_id, period = '7days' } = req.query;
        const userId = req.user.user_id;

        let startDate, endDate = new Date().toISOString().split('T')[0];

        switch (period) {
            case '7days':
                startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                break;
            case '30days':
                startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                break;
            case '3months':
                startDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                break;
            default:
                startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
        }

        const query = `
            SELECT 
                DATE(date) as record_date,
                type,
                SUM(amount) as daily_amount
            FROM records
            WHERE user_id = ?
                AND book_id = ?
                AND is_deleted = 0
                AND date BETWEEN ? AND ?
            GROUP BY DATE(date), type
            ORDER BY record_date ASC
        `;

        const [data] = await db.query(query, [userId, book_id, startDate, endDate]);

        res.json({ code: 200, data });
    } catch (error) {
        console.error('获取趋势数据失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 对比分析（本月vs上月）
router.get('/compare', async (req, res) => {
    try {
        const { book_id } = req.query;
        const userId = req.user.user_id;

        const now = new Date();
        const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
        const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString().split('T')[0];
        const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0).toISOString().split('T')[0];
        const today = now.toISOString().split('T')[0];

        const query = `
            SELECT 
                CASE 
                    WHEN date >= ? THEN 'current'
                    ELSE 'last'
                END as period,
                type,
                SUM(amount) as total_amount,
                COUNT(*) as count
            FROM records
            WHERE user_id = ?
                AND book_id = ?
                AND is_deleted = 0
                AND date >= ?
            GROUP BY period, type
        `;

        const [data] = await db.query(query, [currentMonthStart, userId, book_id, lastMonthStart]);

        const result = {
            current: { income: 0, expense: 0 },
            last: { income: 0, expense: 0 }
        };

        data.forEach(row => {
            result[row.period][row.type] = Number(row.total_amount);
        });

        res.json({ code: 200, data: result });
    } catch (error) {
        console.error('获取对比数据失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// ========================================
// 数据导出
// ========================================

// 导出数据（CSV格式）
router.get('/export', async (req, res) => {
    try {
        const { book_id } = req.query;
        const userId = req.user.user_id;

        console.log('📤 导出请求 - 用户ID:', userId, '账本ID:', book_id);

        // 验证必填参数
        if (!book_id) {
            return res.status(400).json({ 
                code: 400, 
                message: '缺少必填参数：book_id' 
            });
        }

        // 查询记录
        const [records] = await db.query(
            `SELECT date, type, amount, category, remark 
            FROM records
            WHERE user_id = ? AND book_id = ? AND is_deleted = 0
             ORDER BY date DESC`,
            [userId, book_id]
        );

        console.log('📤 查询到记录数:', records.length);

        // 分类中文映射
        const categoryMap = {
            salary: '工资', bonus: '奖金', investment: '投资', gift: '礼金',
            'part-time': '兼职', 'red-packet': '红包', 'other-income': '其他收入',
            food: '餐饮', transport: '交通', shopping: '购物', entertainment: '娱乐',
            healthcare: '医疗', education: '教育', housing: '住房', utilities: '水电',
            'other-expense': '其他支出', other: '其他'
        };

        // 转换为CSV
        let csv = '日期,类型,金额,分类,备注\n';

        records.forEach(record => {
            const date = record.date ? record.date.toString().split('T')[0] : '';
            const type = record.type === 'income' ? '收入' : '支出';
            const amount = record.amount || 0;
            const category = categoryMap[record.category] || record.category || '';
            const remark = (record.remark || '').replace(/,/g, '，'); // 替换逗号避免CSV错误
            
            csv += `${date},${type},${amount},${category},${remark}\n`;
        });

        console.log('✅ CSV生成成功');

        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="export_${Date.now()}.csv"`);
        res.send('\uFEFF' + csv);
    } catch (error) {
        console.error('❌ 导出失败:', error);
        res.status(500).json({ code: 500, message: '导出失败: ' + error.message });
    }
});

// ========================================
// 账本对比
// ========================================

// 账本对比
router.get('/books-compare', async (req, res) => {
    try {
        const userId = req.user.user_id;

        const query = `
            SELECT 
                b.book_id,
                b.book_name,
                b.book_type,
                b.icon,
                b.color,
                COALESCE(SUM(CASE WHEN r.type = 'income' THEN r.amount ELSE 0 END), 0) as total_income,
                COALESCE(SUM(CASE WHEN r.type = 'expense' THEN r.amount ELSE 0 END), 0) as total_expense,
                COUNT(DISTINCT r.record_id) as record_count
            FROM account_books b
            LEFT JOIN records r ON b.book_id = r.book_id AND r.is_deleted = 0
            WHERE b.owner_user_id = ? OR b.book_id IN (
                SELECT book_id FROM book_members WHERE user_id = ?
            )
            GROUP BY b.book_id
            ORDER BY total_expense DESC
        `;

        const [data] = await db.query(query, [userId, userId]);

        res.json({ code: 200, data });
    } catch (error) {
        console.error('账本对比失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

module.exports = router; 